function formatTime(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
}

function formatRoute(time){
	var nowDate = new Date(time);
 var year = nowDate.getFullYear();
 var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
 var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
 var hour = nowDate.getHours()
 var minute = nowDate.getMinutes()
 var dateStr = month + "月" + day+"日" + ' ' + [hour, minute].map(formatNumber).join(':'); //year + "年" + 
 return dateStr;
}

	/**
	 * 格式化日期
	 * @param {Number} time
	 * @param {String} fmt
	 * @return {String}
	 */
//import CryptoJS from './encry/tripledes.js';
var CryptoJS = require('./encry/tripledes.js').CryptoJS;
function format(time, fmt) {
    time = time instanceof Date ? time : new Date(time);
    const o = {
        "M+": time.getMonth() + 1,                 //月份
        "d+": time.getDate(),                    //日
        "h+": time.getHours(),                   //小时
        "m+": time.getMinutes(),                 //分
        "s+": time.getSeconds(),                 //秒
        "q+": Math.floor((time.getMonth() + 3) / 3), //季度
        "S": time.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (const k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
    
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * @param {Object} 行程时间
 * @param {Object} 服务器时间
 */
function formatWeekTips(routeTime,handleTime){
		var diffDay = getDays(routeTime,handleTime);
		var myday ='';
		if(diffDay == 0){//今天出行的						
			myday = '今天';
			return myday;
		}else if(diffDay == 1){
			myday = '明天';
			return myday;
		}else if(diffDay >= 2){
			//再与本周周一的时间对比，显示星期几
			//获取当前日期的星期几
			var week = getWeekFromDate(routeTime);
			var date = handleTime instanceof Date ? handleTime : new Date(handleTime);
			var day = date.getDay() || 7;
			var firstDay = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1 - day);
		//console.info("本周一的日期:"+firstDay);
			var diffweekDay = getDays(routeTime,firstDay);
			//console.info('与本周一对比:'+diffweekDay);
			if(diffweekDay<7){
				week = "本"+week;
			}else if(diffweekDay<14){
				week = "下"+week;
			}else{
				week = "";
			}
			return week;
	}
	return "";
}

function getWeekFromDate(time){
	time = time instanceof Date ? time : new Date(time);
	var week = "周"+"日一二三四五六".charAt(time.getDay());
	return week;
}

/**
 * 获取两个日期之间的天数差
 * @param {Object} time
 * @param {Object} curTime
 */
function getDays(time,curTime){
	time = time instanceof Date ? time : new Date(time);
	curTime = curTime instanceof Date ? curTime : new Date(curTime);
	//先转为00:00:00的时间点
	var firstTime = new Date(time.getFullYear(), time.getMonth(), time.getDate());
	var secondTime =  new Date(curTime.getFullYear(), curTime.getMonth(), curTime.getDate());
	//console.info('firstTime:'+formatRoute(firstTime));
	//console.info('secondTime:'+formatRoute(secondTime));
	var apartTime = firstTime - secondTime;
	var apartDay=parseInt(apartTime / (1000 * 60 * 60 * 24));
	//console.info('相差多少天:'+apartDay);
	return  apartDay;	
}

function formatAudioLength(audioLength){
  var hour=parseInt(audioLength/(60*60));
  var remainTime=audioLength-hour*60*60;

  var minute=parseInt(remainTime/60);
  remainTime=remainTime-minute*60;
  if(hour>0){
    return [hour,minute,remainTime].map(formatNumber).join(":");
  }else {
    return [minute,remainTime].map(formatNumber).join(":");
  }
}

/**
 * 格式化剩余时间
 * params remaindTime 毫秒
 */
function formatRemaindTime(remaindTime){
  var day=parseInt(remaindTime/(1000*60*60*24));
  remaindTime=remaindTime-day*1000*60*60*24;
  var hour=parseInt(remaindTime/(1000*60*60));
  remaindTime=remaindTime-hour*1000*60*60;
  var minute=parseInt(remaindTime/(1000*60));
  remaindTime=remaindTime-minute*1000*60;

  if(day!=0){
    return day+"天"+hour+"小时"+minute+"分"+remaindTime+"秒";
  }
  if(hour>0){
    return hour+"小时"+minute+"分"+remaindTime+"秒";
  }
  if(minute>0){
    return minute+"分"+remaindTime+"秒";
  }
  return remaindTime+"秒";
}

/**
 * 把一个一维数组转换成二维数组
 * param arrayData 一维数组
 * param sliceLength 每个小数组的长度 
 */
function arrayToDoubleArray(arrayData,sliceLength){
  var newArr = new Array();

    if (arrayData == undefined){
        return newArr;
    }
  var subArr=null;
  for(var i =0;i<arrayData.length;i++){
    if((i%sliceLength==0) ||subArr==null){
      subArr = new Array();
      newArr.push(subArr);
    }
    subArr.push(arrayData[i]);
  }
  return newArr;
}


/**
 *
 * @param arr
 * @param num
 */
function to2DimensionArr(arr,num){
    var newArr = new Array();//二维数组

    if (arr == undefined){
        return newArr;
    }
    var subArr=null;
    for(var i =0;i<arr.length;i++){
        var item = arr[i];
        if((i%num==0) ||subArr==null){
            subArr = new Array();//内部的一维数组
            newArr.push(subArr);
        }
        subArr.push(item);
    }
    return newArr;


}

function cloneToObj(newObj,obj){
		if(newObj == null){
			newObj = {};
		}
		//var newObj = {};
		var that = this;
		console.info('onj:'+JSON.stringify(obj));
		for(var key in obj){
			var val = obj[key];
			console.info('value:'+JSON.stringify(val));
			console.info(val);
			if(typeof val === 'object'){				
				//newObj[key] = that.cloneToObj(newObj,val)
			}else{
				console.info('--set vale:'+key);
				console.info('--set value:'+obj[key]);
				newObj[key] = val;
				
			}
			//newObj[key] = typeof val === 'object' ? that.cloneToObj(newObj,val): val;
		}
		return newObj;
	}


function log(msg){
    var isDebug = getApp().globalData.isDebug;
    if (isDebug){
        console.log(msg);
    }
}

function isStrEmpty(str){
    if(str == null || str == '' || str == 'null'|| str == undefined ){
        return true
    }else{
        return false;
    }
}

function objToStr(obj,appendixStr){
    var str = "" ;
    for ( var p in obj ){ // 方法
      if ( typeof ( obj [ p ]) == "function" ){ 
       // obj [ p ]() ; //调用方法

      } else { // p 为属性名称，obj[p]为对应属性的值
        str += p + "=" + obj [ p ] + appendixStr ;
      }
    } 
    return str;
}

function getQiniuOriginalUrl(url){
    if (url.indexOf("http://") == -1){
        url = getApp().globalData.qiNiuHeadUrl +url;
    }

    var index1 = url.indexOf("?");
    if (index1 >0){
        url = url.substring(0,index1);
    }

    return url;

}

function getQiniuSmallPic(url,width,height){

   var  oUrl = getQiniuOriginalUrl(url);

    if (width ==0 || height ==0){
        return oUrl+"?imageMogr2/format/jpg";
    }else {
        return oUrl+"?imageMogr2/thumbnail/!"+width+"x"+height+"r/gravity/Center/crop/"+width+"x"+height;
    }

}

function getBlurPic(url){
    var  oUrl = getQiniuOriginalUrl(url);
    return oUrl+"?imageMogr2/thumbnail/!400x600r/blur/50x99";
}

function getAudioCoverReal(url){
    if(isStrEmpty(url)){
        return "http://static.qxinli.com/HeadPicture/255_2016-02-16_09-52-02_180_180.jpg";
    }

   return getQiniuSmallPic(url,80,80);
}

function refreshUI(that){
    that.setData(that.data);

}

function thressDesDecode(encryStr){
		var keyHex = CryptoJS.enc.Utf8.parse('xUHdKxzVCbsgVIwTnc1jtpWn');
		var decrypt = 	CryptoJS.TripleDES.decrypt(encryStr, keyHex, {    
		iv:CryptoJS.enc.Utf8.parse('01234567'),    
		mode: CryptoJS.mode.CBC,    
		padding: CryptoJS.pad.Pkcs7});
		var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
		console.log('解密结果:'+decryptedStr);
		return decryptedStr;
}

function getDistance(la1,lo1,la2,lo2) {
   console.info(la1+'==='+lo2);
   var La1 = la1 * Math.PI / 180.0;
    var La2 = la2 * Math.PI / 180.0;
    var La3 = La1 - La2;
    var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
    s = s * 6378.137;//地球半径
    s = (Math.round(s * 10000) / 10000).toFixed(1);
    console.log("计算结果",s);
    return s;
}

function isOptStrNull(str){
    if(str == undefined || str == null || str == '' || str == 'null'||str == '[]'||str == '{}'){
        return true
    }else{
        return false;
    }
}
  
module.exports = {
  formatTime: formatTime,
  format:format,
  formatRemaindTime:formatRemaindTime,
  formatAudioLength:formatAudioLength,
  arrayToDoubleArray:arrayToDoubleArray,
	getQiniuSmallPic:getQiniuSmallPic,
	getBlurPic:getBlurPic,
	isStrEmpty:isStrEmpty,
	refreshUI:refreshUI,
	objToStr:objToStr,
	getAudioCoverReal:getAudioCoverReal,
	to2DimensionArr:to2DimensionArr,
	cloneToObj:cloneToObj,
	getWeekFromDate:getWeekFromDate,
	formatRoute:formatRoute,
	formatWeekTips:formatWeekTips,
	thressDesDecode:thressDesDecode,
	getDistance:getDistance,
	isOptStrNull:isOptStrNull
}
